package com.ruoyi.common.distributeLock.configure;

import lombok.Getter;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Objects;

/**
 * @author gim 2023/4/18 15:36
 */
@Component
public class CuratorClient implements DisposableBean {
    private static final Logger log = LoggerFactory.getLogger(CuratorClient.class);
    @Value("${zookeeper.connect}")
    private String connect;

    @Getter
    private CuratorFramework client;

    @PostConstruct
    public void init(){
        this.client= CuratorFrameworkFactory.builder().connectString(connect)
                .sessionTimeoutMs(60*1000)
                .connectionTimeoutMs(15*1000)
                .retryPolicy(new ExponentialBackoffRetry(3000,10))
                .build();
        this.client.start();
    }
    @Override
    public void destroy() throws Exception {
        try{
            if(Objects.nonNull(getClient())){
                getClient().close();
            }
        }catch (Exception e){
            log.debug("CuratorFramework close error=>{}",e.getMessage(),e);
        }
    }
}
